package com.zxg.androidbuslearn.datasave

import android.Manifest
import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.content.SharedPreferences
import android.content.pm.PackageManager
import android.os.Bundle
import android.support.v4.app.ActivityCompat
import android.support.v4.content.ContextCompat
import android.support.v7.app.AppCompatActivity
import android.text.TextUtils
import android.view.View
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
import com.zxg.androidbuslearn.LogUtil
import com.zxg.androidbuslearn.R
import java.security.spec.EncodedKeySpec

/**
 * 作者: 赵小刚
 * 生成时间: 2018/11/15.
 * 版本: 1.0
 * 简介: 文件存储 需要在清单文件中添加操作权限 Android6.0+还需要动态申请权限
 * 修改记录:
 */
class FileActivity : AppCompatActivity(), View.OnClickListener {

    private val PERMISSION_OPER_EXTERNAL_STORAGE = 55
    private val permissions = arrayOf(
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS
    )

    // SD卡操作类型
    private var sdOperType = 0
    private var editText: EditText? = null
    private var textView: TextView? = null
    private var mKey = "mKey"

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_file)

        initView()

        // 测试SharedPreferencesActivity 使用了非共享型数据存储，在其它activity中就读取不到了
        val sp: SharedPreferences = getPreferences(Activity.MODE_PRIVATE)
        val name = sp.getString("name", "")
        LogUtil.logE("FileActivity", "name=" + name)
    }

    // 初始化控件
    private fun initView() {
        editText = findViewById(R.id.edit_text)
        textView = findViewById(R.id.text)
        val saveMemoryBtn = findViewById<Button>(R.id.btn_save_memory)
        saveMemoryBtn.setOnClickListener(this)
        val readMemoryBtn = findViewById<Button>(R.id.btn_read_memory)
        readMemoryBtn.setOnClickListener(this)
        val saveSdBtn = findViewById<Button>(R.id.btn_save_sd)
        saveSdBtn.setOnClickListener(this)
        val readSdBtn = findViewById<Button>(R.id.btn_read_sd)
        readSdBtn.setOnClickListener(this)
    }

    // 按钮点击事件监听
    override fun onClick(v: View?) {
        when (v!!.id) {
            R.id.btn_save_memory -> { // 保存到内存中
                val text = editText!!.text.toString().trim { it <= ' '}
                if (!TextUtils.isEmpty(text)) {
                    val bool = DataUtil.writeMemoryData(this@FileActivity, text)
                    if (bool) {
                        Toast.makeText(this@FileActivity, "写入内存成功!", Toast.LENGTH_LONG).show()
                        editText!!.setText("")
                    } else {
                        Toast.makeText(this, "写入内存失败!", Toast.LENGTH_LONG).show()
                    }
                }
            }
            R.id.btn_read_memory -> { // 读取内存中数据
                val str = DataUtil.readMemoryData(this, mKey)!!.toString()
                textView!!.text = str
            }
            R.id.btn_save_sd -> { // 保存到SD卡中
                applyPermission()
                sdOperType = 1
            }
            R.id.btn_read_sd -> { // 读取SD卡中数据
                applyPermission()
                sdOperType = 2
            }
        }
    }

    // 操作SD卡
    private fun operSD() {
        when (sdOperType) {
            1 -> { // 保存数据到SD卡
                val text = editText!!.text.toString().trim { it <= ' ' }
                if (!TextUtils.isEmpty(text)) {
                    val bool = DataUtil.writeSdData(this, text)
                    if (bool) {
                        Toast.makeText(this@FileActivity, "写入SD卡成功!", Toast.LENGTH_LONG).show()
                        editText!!.setText("")
                    } else {
                        Toast.makeText(this, "写入SD卡失败!", Toast.LENGTH_LONG).show()
                    }
                }
            }
            2 -> { // 读取SD卡数据
                val str = DataUtil.readSdData(this)
                textView!!.text = str
            }
            else -> {

            }
        }
    }

    // 申请权限
    private fun applyPermission() {
        if (!hasPermission(this, *permissions)) {
            requestPermission(this, PERMISSION_OPER_EXTERNAL_STORAGE, *permissions)
        } else {
            operSD()
        }
    }

    // 权限请求回调
    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        when (requestCode) {
            PERMISSION_OPER_EXTERNAL_STORAGE -> { // SD卡读写权限成功
                operSD()
            }
        }
    }

    /**
     * 检查权限是否允许
     * @param permissions 权限数组
     */
    private fun hasPermission(context: Context, vararg permissions: String): Boolean {
        for (permission in permissions) {
            if (ContextCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) {
                return false
            }
        }
        return true
    }

    /**
     * 权限请求
     */
    private fun requestPermission(context: Context, code: Int, vararg permissions: String) {
        ActivityCompat.requestPermissions(context as Activity, permissions, code)
    }
}